import Vuex from "vuex";
import Vue from "vue";
import axios from "axios";
//使用Vuex这个插件
Vue.use(Vuex);

//实例化一个仓库
const store = new Vuex.Store({
  //状态配置
  state: {
    count: 0,
    price: 100,
    num: 0,
    movieList: [],
  },

  //在mutations修改数据的时候，如果有异步操作，可以先在actions中异步操作,然后再提交mutations
  actions: {
    incrementWait(store) {
      setTimeout(() => {
        store.commit("incrementCount");
      }, 2000);
    },
    incrementNWait(store, payload) {
      setTimeout(() => {
        store.commit("incrementNCount", payload);
      }, 2000);
    },

    async getMovieList({ commit }) {
      const result = await axios.get(
        `https://pcw-api.iqiyi.com/search/recommend/list?channel_id=1&data_type=1&mode=11&page_id=2&ret_num=48&session=b9fd987164f6aa47fad266f57dffaa6a`
      );
      console.log(result);

      commit("setMovieList", { movieList: result.data.data.list });
    },
  },

  //对状态的修改配置(mutations是唯一修改vuex中state的途径)
  mutations: {
    incrementCount(state) {
      state.count++;
    },
    incrementNCount(state, { n }) {
      state.count += n;
    },
    setMovieList(state, { movieList }) {
      state.movieList = movieList;
    },
  },

  //vuex中有一个getters配置项,其实就是vuex中的计算属性
  getters: {
    allPrice(state) {
      return state.count * state.price;
    },
  },
});

export default store;
